package com.fxwater.api.controller;

import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.fxwater.common.constant.UserConstants;
import com.fxwater.common.core.domain.AjaxResult;
import com.fxwater.common.utils.StringUtils;
import com.fxwater.common.utils.security.Md5Utils;
import com.fxwater.system.domain.SysUser;
import com.fxwater.system.service.ISysUserService;

@Controller
public class UserController extends ApiBaseController {
    @Autowired
    private ISysUserService userService;
    
    @RequestMapping(value = "/user/login", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult login(String loginName, String password) {
        SysUser user = userService.selectUserByLoginName(loginName);
        if (user == null) {
            logger.warn("登录名不存在，loginName={}", loginName);
            return error("登录名不存在");
        }
        if (user.getStatus().equals(UserConstants.USER_BLOCKED)) {
            return error("账户已被停用");
        }
        if (!user.getPassword().equals(encryptPassword(user.getLoginName(), password, user.getSalt()))) {
            return error("登录名或密码错误");
        }
        user.setToken(StringUtils.generateTokenCode(user.getLoginName()));
        userService.updateUserBasic(user);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", user.getUserId());
        map.put("token", user.getToken());
        return success(map);
    }
    
    public String encryptPassword(String username, String password, String salt) {
        return Md5Utils.hash(username + password + salt);
//        return new Md5Hash(username + password + salt).toHex().toString();
    }
}
